#include <string>
#include <iostream>
#include <fstream>
#include <assert.h>
#include "Shader.h"

std::string& Shader::getSource()
{
	return source;	//return source code of shader
}

Shader::Shader()
{

}

Shader::~Shader()
{
	glDeleteShader(ID);	//cleanup
}

void Shader::loadFromFile(const std::string& filename, GLenum type)
{	
	std::ifstream fin;	
	std::cout<<"Loading shader "<<filename<<"...\n";
	fin.open(filename.c_str());
	assert(fin.is_open() && "Cannot open shader file.");

	//Get number of lines
	while(!fin.eof())
	{
		std::getline(fin, source, '\0');//read in until EOF

	}
	//Start from the top
	fin.close();

	//OpenGL specific code
	ID = glCreateShader(type);
	assert(ID && "Could not Create Shader");
	// Load the shader source 
	const char* s = source.c_str();
    const char** ss = &s;
	glShaderSource(ID, 1, ss, NULL); 
	std::cout<<"Compiling shader "<<filename<<"...\n";
	glCompileShader(ID);

	// Check the compile status
	int compiled;
	glGetShaderiv(ID, GL_COMPILE_STATUS, &compiled);
	if(!compiled)
	{
		GLint infoLen = 0;
		glGetShaderiv(ID, GL_INFO_LOG_LENGTH, &infoLen);
		if(infoLen > 1)
		{
			char* infoLog = new char[infoLen];
			glGetShaderInfoLog(ID, infoLen, NULL, infoLog);
			std::cout<<"Error compiling shader:\n"<< infoLog<<".\n";
			delete infoLog;
		}
		glDeleteShader(ID);	//Delete shader since there was an error	
	}	
}

unsigned int Shader::getID()
{
	return ID;
}


